﻿using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

namespace Utility.BehaviourTree
{
	public abstract class CompositeNode : BTNode
	{
		protected List<BTNode> childNodes = new List<BTNode> ();
		public IEnumerable<BTNode> ChildNodes => childNodes;

		public virtual BTNode Add (params BTNode[] nodes)
		{
			for (int i = 0; i < nodes.Length; i++)
			{
				_AddChild (nodes[i]);
			}
			childNodes.AddRange (nodes);
			return this;
		}

		protected override bool OnPreUpdate ()
		{
			if (childNodes.Count == 0)
			{
				Error ("CompositeNode must have at least one child");
				return false;
			}
			return true;
		}

		protected override bool OnPostUpdate ()
		{
			foreach (var childNode in childNodes)
			{
				if (childNode.IsError)
				{
					Error ("Child node error");
					return false;
				}
			}
			if (!base.OnPostUpdate ())
			{
				return false;
			}
			return true;
		}

		protected override void OnReset ()
		{
			base.OnReset ();
			foreach (var child in childNodes)
			{
				child.Reset ();
			}
		}



		public override StringBuilder BuildString (StringBuilder stringbuilder = null, int depth = 0)
		{
			stringbuilder = base.BuildString (stringbuilder, depth);
			int childDepth = depth + 1;
			foreach (var child in childNodes)
			{
				child.BuildString (stringbuilder, childDepth);
			}
			return stringbuilder;
		}
	}


}